<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>统计 - 记账助手</title>
    <link rel="stylesheet" href="styles.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- 引入Chart.js图表库 -->
    <script src="js/chart.js"></script>
    <style>
        /* 手机端紧凑设计 */
        /* 顶部标题区域样式 */
        .header-controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: white;
            padding: 12px 15px;
            border-bottom: 1px solid #e2e8f0;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        
        /* 统计类型下拉按钮样式 */
        .stats-type-dropdown {
            position: relative;
        }
        .stats-type-btn {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 10px 16px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
            min-width: 80px;
        }
        .stats-type-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
        }
        .dropdown-arrow {
            font-size: 12px;
            transition: transform 0.3s ease;
        }
        .stats-type-btn.active .dropdown-arrow {
            transform: rotate(180deg);
        }
        .stats-type-menu {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border-radius: 12px;
            box-shadow: 0 8px 24px rgba(0,0,0,0.15);
            z-index: 1000;
            margin-top: 8px;
            overflow: hidden;
            display: none;
        }
        .stats-type-option {
            padding: 12px 16px;
            cursor: pointer;
            transition: all 0.2s ease;
            font-size: 15px;
            font-weight: 500;
            color: #374151;
        }
        .stats-type-option:hover {
            background: #f8fafc;
        }
        .stats-type-option.active {
            background: #667eea;
            color: white;
        }
        
        /* 统计周期带框tab样式 */
        .period-tabs {
            display: flex;
            background: #f8fafc;
            border-radius: 12px;
            padding: 4px;
            border: 1px solid #e2e8f0;
        }
        .period-tab {
            padding: 8px 16px;
            border: none;
            background: transparent;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            color: #64748b;
            min-width: 50px;
        }
        .period-tab:hover {
            color: #667eea;
        }
        .period-tab.active {
            background: white;
            color: #667eea;
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.15);
            border: 1px solid #e2e8f0;
        }
        
        /* 时间选择切换样式 - 简洁无边框 */
        .time-tabs {
            background: white;
            padding: 12px 0;
            border-bottom: 1px solid #e2e8f0;
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }
        .time-tabs-container {
            display: flex;
            padding: 0 15px;
            gap: 4px;
            min-width: max-content;
        }
        .time-tab {
            padding: 8px 12px;
            border: none;
            background: transparent;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
            color: #64748b;
            white-space: nowrap;
            flex-shrink: 0;
            position: relative;
        }
        .time-tab:hover {
            color: #667eea;
            background: rgba(102, 126, 234, 0.05);
        }
        .time-tab.active {
            color: #667eea;
            font-weight: 600;
            background: rgba(102, 126, 234, 0.1);
        }
        .time-tab.active::after {
            content: '';
            position: absolute;
            bottom: -12px;
            left: 50%;
            transform: translateX(-50%);
            width: 20px;
            height: 3px;
            background: #667eea;
            border-radius: 2px;
        }
        
        /* 时间选择器弹窗样式 */
        .period-display {
            font-size: 16px;
            font-weight: 600;
            color: #1e293b;
            cursor: pointer;
            padding: 8px 12px;
            border-radius: 8px;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        
        .period-display:hover {
            background: #f1f5f9;
        }
        
        .period-arrow {
            font-size: 12px;
            transition: transform 0.3s ease;
        }
        
        .period-display.active .period-arrow {
            transform: rotate(180deg);
        }
        
        .time-picker {
            position: absolute;
            top: 100%;
            left: 15px;
            right: 15px;
            background: white;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.15);
            z-index: 9999;
            padding: 20px;
            margin-top: 10px;
            display: none;
        }
        
        .time-picker-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .time-nav-btn {
            background: none;
            border: none;
            font-size: 20px;
            color: #667eea;
            cursor: pointer;
            padding: 8px 12px;
            border-radius: 8px;
            transition: all 0.3s ease;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .time-nav-btn:hover {
            background: #f0f5ff;
        }
        
        .time-display {
            font-size: 18px;
            font-weight: 600;
            color: #2d3748;
        }
        
        .time-grid {
            display: grid;
            gap: 12px;
        }
        
        .time-grid.week-grid {
            grid-template-columns: repeat(4, 1fr);
        }
        
        .time-grid.month-grid {
            grid-template-columns: repeat(3, 1fr);
        }
        
        .time-grid.year-grid {
            grid-template-columns: repeat(2, 1fr);
        }
        
        .time-item {
            padding: 12px;
            text-align: center;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
            color: #4a5568;
            border: 1px solid #e2e8f0;
        }
        
        .time-item:hover {
            background: #f0f5ff;
            color: #667eea;
            border-color: #667eea;
        }
        
        .time-item.active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }
        .time-summary-section {
            margin: 0;
            background: white;
            padding: 15px;
            border-bottom: 1px solid #e2e8f0;
        }
        .current-period {
            text-align: center;
            margin-bottom: 12px;
        }
        .period-display {
            font-size: 16px;
            font-weight: 600;
            color: #1e293b;
            cursor: pointer;
            padding: 8px 12px;
            border-radius: 8px;
            transition: all 0.2s ease;
            display: inline-block;
        }
        .period-display:hover {
            background: #f1f5f9;
        }
        .summary-stats {
            display: flex;
            justify-content: space-around;
            gap: 10px;
        }
        .summary-item {
            text-align: center;
            flex: 1;
        }
        .summary-amount {
            font-size: 18px;
            font-weight: 700;
            margin-bottom: 2px;
            color: #1e293b;
        }
        .summary-amount.income {
            color: #10b981;
        }
        .summary-amount.expense {
            color: #ef4444;
        }
        .summary-amount.net {
            color: #667eea;
        }
        .summary-label {
            font-size: 11px;
            color: #64748b;
            font-weight: 500;
        }
        /* 图表标题样式 */
        .chart-title {
            text-align: center;
            font-size: 16px;
            font-weight: 600;
            color: #1e293b;
            padding: 12px 16px;
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
            border-radius: 12px;
            margin: 0;
        }
        .ranking-section {
            margin: 8px 15px 15px;
        }
        .ranking-tabs {
            display: flex;
            margin-bottom: 12px;
            background: white;
            border-radius: 16px;
            padding: 6px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            border: 1px solid rgba(0,0,0,0.05);
        }
        .ranking-tab {
            flex: 1;
            padding: 14px 16px;
            text-align: center;
            background: transparent;
            border: none;
            cursor: pointer;
            font-size: 15px;
            font-weight: 600;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            color: #64748b;
            border-radius: 12px;
        }
        .ranking-tab:hover {
            color: #334155;
            background: rgba(239, 68, 68, 0.05);
        }
        .ranking-tab.active {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            color: white;
            box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
            transform: translateY(-1px);
        }
        .ranking-tab:first-child {
            border-radius: 12px;
        }
        .ranking-tab:last-child {
            border-radius: 12px;
        }
        .category-tabs {
            display: flex;
            margin-bottom: 12px;
            background: white;
            border-radius: 14px;
            padding: 4px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.06);
            border: 1px solid rgba(0,0,0,0.05);
        }
        .category-tab {
            flex: 1;
            padding: 10px 12px;
            text-align: center;
            background: transparent;
            border: none;
            cursor: pointer;
            font-size: 13px;
            font-weight: 600;
            border-radius: 10px;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            color: #64748b;
        }
        .category-tab:hover {
            color: #334155;
            background: rgba(16, 185, 129, 0.05);
        }
        .category-tab.active {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            box-shadow: 0 3px 10px rgba(16, 185, 129, 0.3);
            transform: translateY(-1px);
        }
        .ranking-list {
            background: white;
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            border: 1px solid rgba(0,0,0,0.05);
        }
        .ranking-item {
            display: flex;
            align-items: center;
            padding: 18px 20px;
            border-bottom: 1px solid rgba(0,0,0,0.05);
            transition: all 0.2s ease;
        }
        .ranking-item:hover {
            background: rgba(102, 126, 234, 0.02);
        }
        .ranking-item:last-child {
            border-bottom: none;
        }
        .ranking-rank {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            margin-right: 16px;
            font-size: 14px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .ranking-rank.top1 { 
            background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%); 
            color: #92400e; 
            box-shadow: 0 4px 12px rgba(255, 215, 0, 0.4);
        }
        .ranking-rank.top2 { 
            background: linear-gradient(135deg, #e5e7eb 0%, #d1d5db 100%); 
            color: #374151; 
            box-shadow: 0 4px 12px rgba(209, 213, 219, 0.4);
        }
        .ranking-rank.top3 { 
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); 
            color: white; 
            box-shadow: 0 4px 12px rgba(245, 158, 11, 0.4);
        }
        .ranking-rank.other { 
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%); 
            color: #64748b; 
            box-shadow: 0 2px 6px rgba(0,0,0,0.05);
        }
        .ranking-info {
            flex: 1;
        }
        .ranking-name {
            font-weight: 600;
            margin-bottom: 4px;
            color: #1e293b;
            font-size: 15px;
        }
        .ranking-percent {
            font-size: 12px;
            color: #64748b;
            font-weight: 500;
        }
        .ranking-amount {
            font-weight: 700;
            color: #1e293b;
            font-size: 16px;
        }
        .chart-container {
            margin: 8px 15px;
            background: white;
            border-radius: 16px;
            padding: 20px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            border: 1px solid rgba(0,0,0,0.05);
        }
        
        /* 添加页面整体美化 */
        .app-container {
            background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%);
        }
        
        .header {
            background: rgba(255,255,255,0.95);
            backdrop-filter: blur(20px);
            border-bottom: 1px solid rgba(0,0,0,0.05);
            box-shadow: 0 2px 20px rgba(0,0,0,0.05);
        }
        
        .greeting {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
    </style>
</head>
<body>
    <div class="screen">
        <div class="app-container">
            <!-- 顶部标题区域：统计类型下拉 + 统计周期切换 -->
            <div class="header-controls">
                <div class="stats-type-dropdown">
                    <button class="stats-type-btn" id="stats-type-btn">
                        <span class="stats-type-text">支出</span>
                        <span class="dropdown-arrow">▼</span>
                    </button>
                    <div class="stats-type-menu" id="stats-type-menu">
                        <div class="stats-type-option active" data-type="expense">支出</div>
                        <div class="stats-type-option" data-type="income">收入</div>
                        <div class="stats-type-option" data-type="all">全部</div>
                    </div>
                </div>
                
                <div class="period-tabs">
                    <button class="period-tab" data-period="week">周</button>
                    <button class="period-tab active" data-period="month">月</button>
                    <button class="period-tab" data-period="year">年</button>
                </div>
            </div>
            
            <!-- 时间选择切换 -->
            <div class="time-tabs" id="time-tabs">
                <div class="time-tabs-container">
                    <button class="time-tab" data-time="2024-01">1月</button>
                    <button class="time-tab" data-time="2024-02">2月</button>
                    <button class="time-tab" data-time="2024-03">3月</button>
                    <button class="time-tab" data-time="2024-04">4月</button>
                    <button class="time-tab" data-time="2024-05">5月</button>
                    <button class="time-tab active" data-time="2024-06">6月</button>
                    <button class="time-tab" data-time="2024-07">7月</button>
                    <button class="time-tab" data-time="2024-08">8月</button>
                    <button class="time-tab" data-time="2024-09">9月</button>
                    <button class="time-tab" data-time="2024-10">10月</button>
                    <button class="time-tab" data-time="2024-11">11月</button>
                    <button class="time-tab" data-time="2024-12">12月</button>
                </div>
            </div>
            
            <!-- 时间显示和收支汇总 -->
            <div class="time-summary-section" style="position: relative;">
                <div class="current-period">
                    <div class="period-display" id="period-display">2024年5月第2周 <span class="period-arrow">▼</span></div>
                </div>
                
                <!-- 时间选择器弹窗 -->
                <div class="time-picker" id="time-picker">
                    <div class="time-picker-header">
                        <button class="time-nav-btn" id="prev-time">‹</button>
                        <span class="time-display" id="time-display">2024年</span>
                        <button class="time-nav-btn" id="next-time">›</button>
                    </div>
                    <div class="time-grid" id="time-grid">
                        <!-- 动态生成时间选项 -->
                    </div>
                </div>
                <div class="summary-stats">
                    <div class="summary-item">
                        <div class="summary-amount income" id="total-income">¥2,100</div>
                        <div class="summary-label">收入</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-amount expense" id="total-expense">¥1,350</div>
                        <div class="summary-label">支出</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-amount net" id="net-income">¥750</div>
                        <div class="summary-label">结余</div>
                    </div>
                </div>
            </div>
            
            <!-- 图表选项卡 -->

            
            <!-- 图表容器 -->
            <div class="chart-container">
                <canvas id="trend-chart" height="200"></canvas>
            </div>
            
            <!-- 排行榜部分 -->
            <div class="ranking-section">
                
                <div class="category-tabs">
                    <button class="category-tab active" data-level="1">一级分类</button>
                    <button class="category-tab" data-level="2">二级分类</button>
                </div>
                
                <!-- 饼图统计 -->
                <div class="chart-container" style="margin-bottom: 12px;">
                    <canvas id="pie-chart" height="200"></canvas>
                </div>
                
                <div class="ranking-list" id="ranking-list">
                    <!-- 动态生成排行榜内容 -->
                </div>
            </div>
            
            <div style="height: 80px;"></div> <!-- 底部空间，防止内容被底部导航遮挡 -->
        </div>
            
            <div class="bottom-nav">
                <div class="nav-item" data-page="index.html">
                    <div class="nav-icon">🏠</div>
                    <div>首页</div>
                </div>
                <div class="nav-item active" data-page="statistics.html">
                    <div class="nav-icon">📊</div>
                    <div>统计</div>
                </div>
                <div class="nav-item" id="quick-record-btn">
                    <div class="nav-icon" style="font-size: 24px;">➕</div>
                    <div>记账</div>
                </div>
                <div class="nav-item" data-page="details.html">
                    <div class="nav-icon">📝</div>
                    <div>明细</div>
                </div>
                <div class="nav-item" data-page="user.html">
                    <div class="nav-icon">👤</div>
                    <div>我的</div>
                </div>
            </div>
        </div>
    
    <!-- 一句话记账弹窗 -->
    <div class="quick-record" id="quick-record-modal">
        <div class="quick-record-header">
            <div class="quick-record-title">一句话记账</div>
            <div class="close-btn" id="close-quick-record">✕</div>
        </div>
        <div class="voice-input">
            <input type="text" class="voice-input-field" id="voice-input-field" placeholder="例如：今天午餐花了30元">
            <div class="mic-btn" id="mic-btn">🎤</div>
        </div>
        <button class="btn btn-primary" id="submit-quick-record">识别并记账</button>
    </div>
    
    <!-- 遮罩层 -->
    <div class="overlay" id="overlay"></div>

    <script>
        // 全局变量
        let currentStatsType = 'expense'; // 新增：统计类型（expense/income/all）
        let currentPeriod = 'month'; // 改为默认月
        let currentChart = 'daily';
        let currentRankingType = 'expense';
        let currentCategoryLevel = 1;
        let trendChart = null;
        let pieChart = null;
        let currentSelectedTime = '2024-05'; // 新增：当前选中的时间
        
        // 当前选中的时间
        let currentYear = new Date().getFullYear();
        let currentMonth = new Date().getMonth() + 1;
        let currentWeek = Math.ceil(new Date().getDate() / 7);
        
        // 模拟数据
        const mockData = {
            week: {
                summary: { income: 2100, expense: 1350, net: 750 },
                daily: {
                    labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                    income: [0, 0, 2100, 0, 0, 0, 0],
                    expense: [180, 220, 150, 200, 300, 180, 120]
                }
            },
            month: {
                summary: { income: 8500, expense: 3240, net: 5260 },
                daily: {
                    labels: ['1日', '5日', '10日', '15日', '20日', '25日', '30日'],
                    income: [0, 0, 8500, 0, 0, 0, 0],
                    expense: [200, 350, 500, 400, 600, 450, 740]
                },
                weekly: {
                    labels: ['第1周', '第2周', '第3周', '第4周'],
                    income: [2100, 2000, 2200, 2200],
                    expense: [800, 850, 790, 800]
                }
            },
            year: {
                summary: { income: 102000, expense: 42000, net: 60000 },
                daily: {
                    labels: ['1月1日', '2月1日', '3月1日', '4月1日', '5月1日', '6月1日'],
                    income: [0, 0, 8500, 8100, 8500, 8200],
                    expense: [3500, 3200, 3240, 3100, 3400, 3300]
                },
                weekly: {
                    labels: ['第1周', '第10周', '第20周', '第30周', '第40周', '第50周'],
                    income: [2100, 2000, 2200, 2100, 2300, 2200],
                    expense: [800, 850, 790, 820, 780, 800]
                },
                monthly: {
                    labels: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
                    income: [8000, 7500, 8500, 8100, 8500, 8200, 8300, 8400, 8600, 8800, 8700, 8900],
                    expense: [3500, 3200, 3240, 3100, 3400, 3300, 3450, 3600, 3550, 3700, 3650, 3800]
                }
            }
        };
        
        const rankingData = {
            expense: {
                level1: [
                    { name: '餐饮', amount: 1200, percent: 37 },
                    { name: '购物', amount: 800, percent: 25 },
                    { name: '住房', amount: 500, percent: 15 },
                    { name: '交通', amount: 300, percent: 9 },
                    { name: '娱乐', amount: 300, percent: 9 },
                    { name: '通讯', amount: 200, percent: 6 }
                ],
                level2: [
                    { name: '外卖', amount: 600, percent: 18 },
                    { name: '聚餐', amount: 400, percent: 12 },
                    { name: '服装', amount: 500, percent: 15 },
                    { name: '数码', amount: 300, percent: 9 },
                    { name: '房租', amount: 500, percent: 15 },
                    { name: '打车', amount: 200, percent: 6 }
                ]
            },
            income: {
                level1: [
                    { name: '工资', amount: 7500, percent: 88 },
                    { name: '兼职', amount: 500, percent: 6 },
                    { name: '理财', amount: 300, percent: 4 },
                    { name: '礼金', amount: 200, percent: 2 }
                ],
                level2: [
                    { name: '基本工资', amount: 6000, percent: 71 },
                    { name: '绩效奖金', amount: 1500, percent: 18 },
                    { name: '设计兼职', amount: 300, percent: 4 },
                    { name: '写作兼职', amount: 200, percent: 2 },
                    { name: '基金收益', amount: 200, percent: 2 },
                    { name: '股票收益', amount: 100, percent: 1 }
                ]
            }
        };
        
        // 更新当前日期显示
        function updateDate() {
            let dateText = '';
            if (currentPeriod === 'week') {
                dateText = `${currentYear}年${currentMonth}月第${currentWeek}周`;
            } else if (currentPeriod === 'month') {
                dateText = `${currentYear}年${currentMonth}月`;
            } else {
                dateText = `${currentYear}年`;
            }
            
            const periodDisplay = document.getElementById('period-display');
            if (periodDisplay) {
                periodDisplay.textContent = dateText;
            }
        }
        
        // 生成动态收支数据
        function generateSummaryData() {
            // 根据时间生成不同的数据（模拟真实数据变化）
            const baseIncome = currentPeriod === 'year' ? 120000 : currentPeriod === 'month' ? 10000 : 2500;
            const baseExpense = currentPeriod === 'year' ? 80000 : currentPeriod === 'month' ? 6500 : 1600;
            
            // 添加时间相关的变化因子
            const timeFactor = (currentYear - 2020) * 0.1 + (currentMonth - 1) * 0.05 + currentWeek * 0.02;
            const randomFactor = Math.sin(currentYear + currentMonth + currentWeek) * 0.2;
            
            const income = Math.round(baseIncome * (1 + timeFactor + randomFactor));
            const expense = Math.round(baseExpense * (1 + timeFactor * 0.8 + randomFactor * 0.5));
            const net = income - expense;
            
            return { income, expense, net };
        }
        
        // 更新总收支显示
        function updateSummary() {
            const data = generateSummaryData();
            document.getElementById('total-income').textContent = `¥${data.income.toLocaleString()}`;
            document.getElementById('total-expense').textContent = `¥${data.expense.toLocaleString()}`;
            document.getElementById('net-income').textContent = `¥${data.net.toLocaleString()}`;
        }
        
        // 生成动态图表数据
        function generateChartData() {
            let labels = [];
            let incomeData = [];
            let expenseData = [];
            
            if (currentPeriod === 'year' && currentChart === 'monthly') {
                // 年统计显示月度数据
                const baseIncome = 8500;
                const baseExpense = 3500;
                
                for (let month = 1; month <= 12; month++) {
                    labels.push(`${month}月`);
                    const monthFactor = Math.sin(month / 6) * 0.2 + (currentYear - 2020) * 0.05;
                    const randomFactor = (Math.random() - 0.5) * 0.3;
                    incomeData.push(Math.round(baseIncome * (1 + monthFactor + randomFactor)));
                    expenseData.push(Math.round(baseExpense * (1 + monthFactor * 0.8 + randomFactor * 0.5)));
                }
            } else if (currentChart === 'daily') {
                // 月和周统计显示日数据
                const baseIncome = currentPeriod === 'month' ? 280 : 350;
                const baseExpense = currentPeriod === 'month' ? 180 : 220;
                const days = currentPeriod === 'month' ? 30 : 7;
                
                for (let i = 1; i <= days; i++) {
                    if (currentPeriod === 'month') {
                        labels.push(`${i}日`);
                    } else {
                        const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
                        labels.push(weekdays[i-1]);
                    }
                    
                    const dayFactor = Math.sin(i / 7) * 0.3 + (Math.random() - 0.5) * 0.4;
                    incomeData.push(Math.round(baseIncome * (1 + dayFactor)));
                    expenseData.push(Math.round(baseExpense * (1 + dayFactor * 0.7)));
                }
            }
            
            return { labels, income: incomeData, expense: expenseData };
        }
        
        // 更新图表
        function updateChart() {
            const chartData = generateChartData();
            
            const ctx = document.getElementById('trend-chart').getContext('2d');
            
            if (trendChart) {
                trendChart.destroy();
            }
            
            trendChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: chartData.labels,
                    datasets: [
                        {
                            label: '收入',
                            data: chartData.income,
                            borderColor: '#51cf66',
                            backgroundColor: 'rgba(81, 207, 102, 0.1)',
                            borderWidth: 2,
                            fill: true,
                            tension: 0.4
                        },
                        {
                            label: '支出',
                            data: chartData.expense,
                            borderColor: '#ff6b6b',
                            backgroundColor: 'rgba(255, 107, 107, 0.1)',
                            borderWidth: 2,
                            fill: true,
                            tension: 0.4
                        }
                    ]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    },
                    plugins: {
                        legend: {
                            position: 'top'
                        }
                    }
                }
            });
        }
        
        // 更新排行榜
        function updateRanking() {
            const data = rankingData[currentRankingType][`level${currentCategoryLevel}`];
            const container = document.getElementById('ranking-list');
            
            container.innerHTML = '';
            
            data.forEach((item, index) => {
                const rankClass = index === 0 ? 'top1' : index === 1 ? 'top2' : index === 2 ? 'top3' : 'other';
                
                const rankingItem = document.createElement('div');
                rankingItem.className = 'ranking-item';
                rankingItem.style.cursor = 'pointer';
                rankingItem.innerHTML = `
                    <div class="ranking-rank ${rankClass}">${index + 1}</div>
                    <div class="ranking-info">
                        <div class="ranking-name">${item.name}</div>
                        <div class="ranking-percent">占比 ${item.percent}%</div>
                    </div>
                    <div class="ranking-amount">¥${item.amount.toLocaleString()}</div>
                `;
                
                // 添加点击事件，跳转到分类详情页面
                rankingItem.addEventListener('click', function() {
                    const categoryName = encodeURIComponent(item.name);
                    const categoryType = currentRankingType;
                    const categoryLevel = currentCategoryLevel;
                    window.location.href = `category-detail.html?category=${categoryName}&type=${categoryType}&level=${categoryLevel}`;
                });
                
                container.appendChild(rankingItem);
            });
        }
        
        // 更新饼图
        function updatePieChart() {
            const data = rankingData[currentRankingType][`level${currentCategoryLevel}`];
            const ctx = document.getElementById('pie-chart').getContext('2d');
            
            // 准备饼图数据
            const labels = data.map(item => item.name);
            const values = data.map(item => item.amount);
            
            // 生成颜色
            const backgroundColors = [
                'rgba(255, 99, 132, 0.7)',
                'rgba(54, 162, 235, 0.7)',
                'rgba(255, 206, 86, 0.7)',
                'rgba(75, 192, 192, 0.7)',
                'rgba(153, 102, 255, 0.7)',
                'rgba(255, 159, 64, 0.7)',
                'rgba(199, 199, 199, 0.7)',
                'rgba(83, 102, 255, 0.7)',
                'rgba(40, 159, 64, 0.7)',
                'rgba(210, 199, 199, 0.7)'
            ];
            
            // 销毁旧图表
            if (pieChart) {
                pieChart.destroy();
            }
            
            // 创建新图表
            pieChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: labels,
                    datasets: [{
                        data: values,
                        backgroundColor: backgroundColors.slice(0, data.length),
                        borderColor: backgroundColors.map(color => color.replace('0.7', '1')),
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            position: 'right',
                            labels: {
                                boxWidth: 15,
                                font: {
                                    size: 11
                                }
                            }
                        },
                        title: {
                            display: true,
                            text: currentStatsType === 'expense' ? '支出分布' : currentStatsType === 'income' ? '收入分布' : '收支分布',
                            font: {
                                size: 16
                            }
                        }
                    },
                    cutout: '50%'
                }
            });
        }
        
        // 初始化时间选择器弹窗
        function initTimePicker() {
            const periodDisplay = document.getElementById('period-display');
            const timePicker = document.getElementById('time-picker');
            const prevTimeBtn = document.getElementById('prev-time');
            const nextTimeBtn = document.getElementById('next-time');
            
            // 点击时间显示弹出选择器
            periodDisplay.addEventListener('click', function() {
                const isVisible = timePicker.style.display !== 'none';
                timePicker.style.display = isVisible ? 'none' : 'block';
                periodDisplay.classList.toggle('active', !isVisible);
                if (!isVisible) {
                    updateTimePicker();
                }
            });
            
            // 时间导航按钮
            prevTimeBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                navigateTime(-1);
            });
            
            nextTimeBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                navigateTime(1);
            });
            
            // 点击其他地方关闭选择器
            document.addEventListener('click', function(e) {
                if (!periodDisplay.contains(e.target) && !timePicker.contains(e.target)) {
                    timePicker.style.display = 'none';
                    periodDisplay.classList.remove('active');
                }
            });
        }
        
        // 更新时间选择器内容
        function updateTimePicker() {
            const timeDisplay = document.getElementById('time-display');
            const timeGrid = document.getElementById('time-grid');
            
            timeGrid.innerHTML = '';
            
            if (currentPeriod === 'year') {
                timeDisplay.textContent = '选择年份';
                timeGrid.className = 'time-grid year-grid';
                
                for (let year = currentYear - 5; year <= currentYear + 5; year++) {
                    const item = document.createElement('div');
                    item.className = 'time-item';
                    if (year === currentYear) item.classList.add('active');
                    item.textContent = year + '年';
                    item.addEventListener('click', function() {
                        currentYear = year;
                        updateAll();
                        document.getElementById('time-picker').style.display = 'none';
                        document.getElementById('period-display').classList.remove('active');
                    });
                    timeGrid.appendChild(item);
                }
            } else if (currentPeriod === 'month') {
                timeDisplay.textContent = currentYear + '年';
                timeGrid.className = 'time-grid month-grid';
                
                for (let month = 1; month <= 12; month++) {
                    const item = document.createElement('div');
                    item.className = 'time-item';
                    if (month === currentMonth) item.classList.add('active');
                    item.textContent = month + '月';
                    item.addEventListener('click', function() {
                        currentMonth = month;
                        updateAll();
                        document.getElementById('time-picker').style.display = 'none';
                        document.getElementById('period-display').classList.remove('active');
                    });
                    timeGrid.appendChild(item);
                }
            } else if (currentPeriod === 'week') {
                timeDisplay.textContent = currentYear + '年' + currentMonth + '月';
                timeGrid.className = 'time-grid week-grid';
                
                for (let week = 1; week <= 5; week++) {
                    const item = document.createElement('div');
                    item.className = 'time-item';
                    if (week === currentWeek) item.classList.add('active');
                    item.textContent = '第' + week + '周';
                    item.addEventListener('click', function() {
                        currentWeek = week;
                        updateAll();
                        document.getElementById('time-picker').style.display = 'none';
                        document.getElementById('period-display').classList.remove('active');
                    });
                    timeGrid.appendChild(item);
                }
            }
        }
        
        // 时间导航函数
        function navigateTime(direction) {
            if (currentPeriod === 'year') {
                currentYear += direction;
            } else if (currentPeriod === 'month') {
                currentMonth += direction;
                if (currentMonth > 12) {
                    currentMonth = 1;
                    currentYear++;
                } else if (currentMonth < 1) {
                    currentMonth = 12;
                    currentYear--;
                }
            } else { // week
                currentWeek += direction;
                if (currentWeek > 5) {
                    currentWeek = 1;
                    currentMonth++;
                    if (currentMonth > 12) {
                        currentMonth = 1;
                        currentYear++;
                    }
                } else if (currentWeek < 1) {
                    currentWeek = 5;
                    currentMonth--;
                    if (currentMonth < 1) {
                        currentMonth = 12;
                        currentYear--;
                    }
                }
            }
            
            updateTimePicker();
            updateAll();
        }
        
        // 更新时间选择标签
        function updateTimeTabs() {
            const timeTabsContainer = document.querySelector('.time-tabs-container');
            let tabs = '';
            
            if (currentPeriod === 'week') {
                // 生成周的选项
                for (let week = 1; week <= 5; week++) {
                    const isActive = week === currentWeek ? 'active' : '';
                    tabs += `<button class="time-tab ${isActive}" data-time="${currentYear}-${currentMonth}-W${week}">第${week}周</button>`;
                }
            } else if (currentPeriod === 'month') {
                // 生成月的选项
                for (let month = 1; month <= 12; month++) {
                    const isActive = month === currentMonth ? 'active' : '';
                    const monthStr = month.toString().padStart(2, '0');
                    tabs += `<button class="time-tab ${isActive}" data-time="${currentYear}-${monthStr}">${month}月</button>`;
                }
            } else if (currentPeriod === 'year') {
                // 生成年的选项
                for (let year = currentYear - 3; year <= currentYear + 2; year++) {
                    const isActive = year === currentYear ? 'active' : '';
                    tabs += `<button class="time-tab ${isActive}" data-time="${year}">${year}年</button>`;
                }
            }
            
            timeTabsContainer.innerHTML = tabs;
            
            // 重新绑定时间选择事件
            document.querySelectorAll('.time-tab').forEach(tab => {
                tab.addEventListener('click', function() {
                    document.querySelectorAll('.time-tab').forEach(t => t.classList.remove('active'));
                    this.classList.add('active');
                    
                    const timeValue = this.getAttribute('data-time');
                    if (currentPeriod === 'week') {
                        const parts = timeValue.split('-');
                        currentYear = parseInt(parts[0]);
                        currentMonth = parseInt(parts[1]);
                        currentWeek = parseInt(parts[2].replace('W', ''));
                    } else if (currentPeriod === 'month') {
                        const parts = timeValue.split('-');
                        currentYear = parseInt(parts[0]);
                        currentMonth = parseInt(parts[1]);
                    } else if (currentPeriod === 'year') {
                        currentYear = parseInt(timeValue);
                    }
                    
                    currentSelectedTime = timeValue;
                    updateAll();
                });
            });
        }
        
        // 初始化下拉菜单
        function initStatsTypeDropdown() {
            const statsTypeBtn = document.getElementById('stats-type-btn');
            const statsTypeMenu = document.getElementById('stats-type-menu');
            const statsTypeText = document.querySelector('.stats-type-text');
            
            // 点击按钮切换下拉菜单
            statsTypeBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                const isVisible = statsTypeMenu.style.display === 'block';
                statsTypeMenu.style.display = isVisible ? 'none' : 'block';
                statsTypeBtn.classList.toggle('active', !isVisible);
            });
            
            // 选择选项
            document.querySelectorAll('.stats-type-option').forEach(option => {
                option.addEventListener('click', function() {
                    // 更新选中状态
                    document.querySelectorAll('.stats-type-option').forEach(o => o.classList.remove('active'));
                    this.classList.add('active');
                    
                    // 更新按钮文本
                    statsTypeText.textContent = this.textContent;
                    
                    // 更新全局状态
                    currentStatsType = this.getAttribute('data-type');
                    currentRankingType = currentStatsType === 'all' ? 'expense' : currentStatsType;
                    
                    // 关闭下拉菜单
                    statsTypeMenu.style.display = 'none';
                    statsTypeBtn.classList.remove('active');
                    
                    // 更新页面内容
                    updateAll();
                });
            });
            
            // 点击其他地方关闭下拉菜单
            document.addEventListener('click', function(e) {
                if (!statsTypeBtn.contains(e.target) && !statsTypeMenu.contains(e.target)) {
                    statsTypeMenu.style.display = 'none';
                    statsTypeBtn.classList.remove('active');
                }
            });
        }
        
        // 初始化事件监听
        function initEventListeners() {
            // 初始化统计类型下拉菜单
            initStatsTypeDropdown();
            
            // 时间周期切换
            document.querySelectorAll('.period-tab').forEach(btn => {
                btn.addEventListener('click', function() {
                    document.querySelectorAll('.period-tab').forEach(b => b.classList.remove('active'));
                    this.classList.add('active');
                    currentPeriod = this.getAttribute('data-period');
                    updateTimeTabs(); // 更新时间选择标签
                    updateAll();
                });
            });
            
            // 初始化时间选择器
            initTimePicker();
            
            // 注释掉排行榜类型切换，因为已经移到顶部统计类型切换
            // document.querySelectorAll('.ranking-tab').forEach(tab => {
            //     tab.addEventListener('click', function() {
            //         document.querySelectorAll('.ranking-tab').forEach(t => t.classList.remove('active'));
            //         this.classList.add('active');
            //         currentRankingType = this.getAttribute('data-type');
            //         updateRanking();
            //     });
            // });
            
            // 分类级别切换
            document.querySelectorAll('.category-tab').forEach(tab => {
                tab.addEventListener('click', function() {
                    document.querySelectorAll('.category-tab').forEach(t => t.classList.remove('active'));
                    this.classList.add('active');
                    currentCategoryLevel = this.getAttribute('data-level');
                    updateRanking();
                });
            });
            
            // 底部导航
            document.querySelectorAll('.nav-item[data-page]').forEach(item => {
                item.addEventListener('click', function() {
                    window.location.href = this.getAttribute('data-page');
                });
            });
            
            // 一句话记账功能
            const quickRecordBtn = document.getElementById('quick-record-btn');
            const quickRecordModal = document.getElementById('quick-record-modal');
            const closeQuickRecord = document.getElementById('close-quick-record');
            const overlay = document.getElementById('overlay');
            
            quickRecordBtn.addEventListener('click', function() {
                quickRecordModal.classList.add('active');
                overlay.classList.add('active');
            });
            
            closeQuickRecord.addEventListener('click', function() {
                quickRecordModal.classList.remove('active');
                overlay.classList.remove('active');
            });
            
            // 麦克风按钮
            const micBtn = document.getElementById('mic-btn');
            const voiceInputField = document.getElementById('voice-input-field');
            
            micBtn.addEventListener('click', function() {
                showAlert('正在启动语音识别...');
                setTimeout(() => {
                    voiceInputField.value = '今天午餐花了45元';
                }, 1500);
            });
            
            // 提交记账
            const submitQuickRecord = document.getElementById('submit-quick-record');
            submitQuickRecord.addEventListener('click', function() {
                const inputText = voiceInputField.value.trim();
                if (!inputText) {
                    showAlert('请输入或语音录入记账内容');
                    return;
                }
                
                showAlert('正在识别内容...');
                setTimeout(() => {
                    quickRecordModal.classList.remove('active');
                    overlay.classList.remove('active');
                    window.location.href = 'index.html';
                }, 1500);
            });
        }
        
        // 更新所有内容
        function updateAll() {
            updateDate();
            updateSummary();
            updateChart();
            updateRanking();
            updatePieChart();
            updateTimeTabs(); // 添加时间选择标签更新
        }
        
        // Bootstrap 模态框函数
        function showAlert(message) {
            document.getElementById('alertModalBody').textContent = message;
            const alertModal = new bootstrap.Modal(document.getElementById('alertModal'));
            alertModal.show();
        }
        
        // 页面加载完成后初始化
        window.addEventListener('load', function() {
            initEventListeners();
            updateAll();
        });
    </script>

    <!-- Bootstrap 模态框 -->
    <div class="modal fade" id="alertModal" tabindex="-1" aria-labelledby="alertModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="alertModalLabel">提示</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="alertModalBody">
                    <!-- 动态内容 -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal">确定</button>
                </div>
            </div>
        </div>
    </div>
</body>
</html>